package com.wangxl;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 测试序列化
 * @author wangxl
 * @date 2022/2/17 16:08
 */
@Slf4j
public class SerializableTest {

    /**
     * 向文件obj.dat中写入对象信息
     * @param obj 对象
     */
    public static void wirte(Object obj){
        File file = new File("d:/obj.dat");
        FileOutputStream out = null;
        ObjectOutputStream oos = null;
        try {
            out = new FileOutputStream(file, false);
            oos = new ObjectOutputStream(out);
            oos.writeObject(obj);
            // flush的作用：强制性地将缓存中的数据发出去
            oos.flush();
            System.out.println("write successful");
        } catch (NotSerializableException e){
            log.info("NotSerializableException" + e.getMessage());
        } catch (IOException e) {
            log.info("IO异常" + e.getMessage());
        } finally {
            if (null != oos){
                try {
                    oos.close();
                } catch (IOException e) {
                    log.info("IO异常" + e.getMessage());
                }
            }
            if (null != out){
                try {
                    out.close();
                } catch (IOException e) {
                    log.info("IO异常" + e.getMessage());
                }
            }
        }
    }

    public static void main(String[] args) {
        Person person = new Person("wxl",23);

        Student student = new Student("zhangsan",25);

        // 把实现序列化接口的student对象存入文件中
        SerializableTest.wirte(student);

        // 把没有实现序列化接口的person对象存入文件中，会抛出NotSerializableException异常
        SerializableTest.wirte(person);

    }

}
